/*-+-*****************************************************************************
 Copyright (C) 2009-2012 Oceanside Software Corporation (R)
 Dallas, Texas

 Author       : Jason T. Brower
 Purpose      : This file is part of a point-of-sale software package
                originally written for Table-Service Restaurants.
              
 Date         : July 8th of 2012
              
 History      : The application that this software file belongs to was 
                written over a 3-Year period.  The first version was written
                in C# .Net 3.5 using Windows Forms.  Being new to .Net at
                the time, I soon learned of Windows Presentation Foundation,
                liked the graphics capabilities and databinding so I
                migrated to WPF.  When the .Net 4.0 framework was released
                the application was migrated from 3.5 to 4.0. Now today,
                .Net 4.5 RC is out and I was already in process of migrating
                before I made this public.
                
Excuse Me     : Please excuse the coding style, it is not representative of
                my typical work.  During the three years I was under a very
                tight budget, constantly running out of funding and was 
                working 18 hour days hyped up on 5-Hour Energy.  The 
                design is not textbook.  It is monolythic because of
                previous issues I will not get into.  There are few comments
                in the code and the ones that are there may be incorrect.
                
What it is not: This is not the exact version that I took through PA-DSS 2.0
                nor is it the exact version running at my customer sites.
                I removed some details for security purposes including some
                encryption algorithms.  The reporting was removed because
                I was including a third party library that cannot be 
                published with this Open Source.
                
What it is    : This application has been running at high volume restaraunts
                for over a year.  It never freezes, crashes or does anything
                unexpected.  So long as it is built, installed and configured
                correctly, it is a strong system that we can all enhance.

Contact       : Please note that I can no longer work for free.  However, you
                can reach me at information@oceansidesw.com.                                                      

*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
#if _LOCALDB
  using Oceanside.LocalDB;
#else
using Oceanside.RemoteDB;
#endif

#if _LOCALDB
  namespace Oceanside.LocalDB
#else
namespace Oceanside.RemoteDB
#endif
{
    /// <summary>
    /// Became a dumping ground for random things.
    /// </summary>
    public class CommonCalls
    {
        public enum REPORT_TYPE_ENUM
        {
            SALES_DAYPART,
            SALES_EMPLOYEE,
            SALES_PRODUCTGROUP,
            SALES_REVCENTER,
            SALES_REVTYPE,
            SALES_DAYOFWEEK,
            VOIDS_BYTYPE,
            COMPS_BYTYPE,
            PROMO_BYTYPE,
            VOIDS_BYMANAGER,
            COMPS_BYMANAGER,
            PROMO_BYMANAGER,
            VOIDS_BYEMPLOYEE,
            COMPS_BYEMPLOYEE,
            PROMO_BYEMPLOYEE
        };

        public static decimal GetPaidIns(IEnumerable<BUSINESS_DAY> bdays)
        {
            decimal paidIns = 0;
            try
            {
                var paidInsQ = bdays.SelectMany(bd => bd.SHIFTS.SelectMany(s => s.PAYMENTS).Where(p => p.WasPaidIn));
                if (paidInsQ.Any())
                {
                    paidIns = paidInsQ.Sum(p => p.Amount);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return paidIns;
        }

        public static decimal GetPaidOuts(IEnumerable<BUSINESS_DAY> bdays)
        {
            decimal paidOuts = 0;
            try
            {
                var paidOutsQ = bdays.SelectMany(bd => bd.SHIFTS.SelectMany(s => s.PAYMENTS).Where(p => !p.WasPaidIn));
                if (paidOutsQ.Any())
                {
                    paidOuts = paidOutsQ.Sum(p => p.Amount);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return paidOuts;
        }

        public static decimal GetBusinessDayStarts(IEnumerable<BUSINESS_DAY> bdays)
        {
            decimal deposits = 0;
            try
            {
                var depositsQ = bdays.SelectMany(bd => bd.DEPOSIT).Where(d => d.Amount > 0 && d.Type == null);
                if (depositsQ.Any())
                {
                    deposits = depositsQ.Sum(p => p.Amount);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return deposits;
        }

        public static List<ORDER> GetOrders(IEnumerable<BUSINESS_DAY> bdays)
        {
            List<ORDER> ordersList = new List<ORDER>();
            try
            {
                var ordersQ = bdays.SelectMany(b => b.SHIFTS.SelectMany(o => o.ORDERS));
                if (ordersQ.Any())
                {
                    ordersList.AddRange(ordersQ);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return ordersList;
        }

        public static List<ORDER> GetOrders(IEnumerable<SHIFT> shifts)
        {
            List<ORDER> ordersList = new List<ORDER>();
            try
            {
                var ordersQ = shifts.SelectMany(o => o.ORDERS);
                if (ordersQ.Any())
                {
                    ordersList.AddRange(ordersQ);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return ordersList;
        }

        public static List<SALE> GetNonSeeServerSales(IEnumerable<BUSINESS_DAY> bdays)
        {
            List<SALE> salesList = new List<SALE>();
            try
            {
                var salesQ = bdays.SelectMany(bd => bd.SHIFTS.SelectMany(sh => sh.ORDERS.SelectMany(sa => sa.SALES.Where(s => !s.IsSeeServer))));
                if (salesQ.Any())
                {
                    salesList.AddRange(salesQ);
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return salesList;
        }
        public static decimal GetNetSales(IEnumerable<BUSINESS_DAY> bdays)
        {
            decimal netSales = 0;
            try
            {
                List<ORDER> orders = GetOrders(bdays);
                if (orders.Any())
                {
                    netSales = (from o in orders select o.RoundedSalesSubtotal).Sum();
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return netSales;
        }

        public static decimal GetExclusiveTaxInfo(IEnumerable<BUSINESS_DAY> bdays, out decimal outExclTaxable)
        {
            outExclTaxable = 0;
            decimal exclusiveTaxes = 0;

            try
            {
                List<ORDER> orders = GetOrders(bdays);
                if (orders.Any())
                {
                    decimal totalTaxable = 0;
                    var exclusiveTaxesQ = (from o in orders
                                           let ExclusiveTaxPerOrder = ORDER.SalesExclusiveTaxTotal(o.SALES.ToList(), out totalTaxable)
                                           let ExclusivelyTaxable = totalTaxable
                                           select new
                                           {
                                               Tax = ExclusiveTaxPerOrder,
                                               Taxable = ExclusivelyTaxable,
                                           }
                                               into exlusivelyTaxable
                                               select exlusivelyTaxable);

                    if (exclusiveTaxesQ.Any())
                    {
                        exclusiveTaxes = exclusiveTaxesQ.Sum(t => t.Tax);
                        outExclTaxable = exclusiveTaxesQ.Sum(t => t.Taxable);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return exclusiveTaxes;
        }

        public static decimal GetInclusiveTaxInfo(IEnumerable<BUSINESS_DAY> bdays, out decimal outInclTaxable)
        {
            outInclTaxable = 0;
            decimal inclusiveTaxes = 0;

            try
            {
                List<SALE> nonSeeServerSales = GetNonSeeServerSales(bdays);
                if (nonSeeServerSales.Any())
                {
                    var inclusiveTaxesQ = (from s in nonSeeServerSales
                                           where !s.WasCompedInEntire && !s.WasVoided && s.InclusiveTaxRate != 0
                                           let DiscountAmount = s.CountOrdered * (s.ActualPrice * s.DiscountRate)
                                           let DiscountedPrice = (s.CountOrdered * s.ActualPrice) - DiscountAmount
                                           let IncTaxPerSale = (DiscountedPrice - (DiscountedPrice / (1 + s.InclusiveTaxRate)))
                                           select new
                                           {
                                               Tax = IncTaxPerSale,
                                               Taxable = DiscountedPrice,
                                           }
                                               into inlusivelyTaxable
                                               select inlusivelyTaxable);

                    if (inclusiveTaxesQ.Any())
                    {
                        inclusiveTaxes = inclusiveTaxesQ.Sum(t => t.Tax);
                        outInclTaxable = inclusiveTaxesQ.Sum(t => t.Taxable);
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return inclusiveTaxes;
        }

        public static decimal GetAutoGratuity(IEnumerable<BUSINESS_DAY> bdays)
        {
            decimal autograt = 0;
            List<ORDER> ordersList = GetOrders(bdays);
            foreach (ORDER o in ordersList)
            {
                for (int i = 0; i < o.CheckCount; i++)
                {
                    autograt += o.GetChecksAutoGratutiy(i);
                }
            }

            return autograt;
        }

        public static decimal GetAutoGratuity(IEnumerable<SHIFT> shifts)
        {
            decimal autograt = 0;
            List<ORDER> ordersList = GetOrders(shifts);
            foreach (ORDER o in ordersList)
            {
                for (int i = 0; i < o.CheckCount; i++)
                {
                    autograt += o.GetChecksAutoGratutiy(i);
                }
            }

            return autograt;
        }

        public static decimal GetNonTaxableSalesTotal(IEnumerable<BUSINESS_DAY> bdays)
        {
            decimal nonTaxable = 0;
            try
            {
                List<SALE> nonSeeServerSales = GetNonSeeServerSales(bdays);
                if (nonSeeServerSales.Any())
                {
                    nonTaxable = (from s in nonSeeServerSales
                                  where !s.WasCompedInEntire && !s.WasVoided && s.ExclusiveTaxRate == 0 && s.InclusiveTaxRate == 0
                                  let DiscountAmount = s.CountOrdered * (s.ActualPrice * s.DiscountRate)
                                  let DiscountedPrice = (s.CountOrdered * s.ActualPrice) - DiscountAmount
                                  select DiscountedPrice).DefaultIfEmpty().Sum();
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return nonTaxable;
        }

        public static void GetGuestInfo(IEnumerable<BUSINESS_DAY> bdays,
            out decimal checkCount,
            out decimal checkAverage,
            out decimal guestCount,
            out decimal ppa)
        {
            checkCount = 0;
            guestCount = 0;
            checkAverage = 0;
            ppa = 0;

            try
            {
                List<ORDER> orders = GetOrders(bdays);
                decimal netSales = CommonCalls.GetNetSales(bdays);
                if (orders.Any())
                {
                    checkCount = (from o in orders select o.CheckCount).DefaultIfEmpty().Sum();
                    guestCount = (from o in orders select o.GuestCount).DefaultIfEmpty().Sum();
                    ppa = guestCount == 0 ? 0 : netSales / guestCount;
                    checkAverage = checkCount == 0 ? 0 : netSales / checkCount;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        public static decimal GetCashDepositInfo(IEnumerable<BUSINESS_DAY> bdays, out string notes)
        {
            notes = "N/A";
            decimal cashDeposits = 0;
            try
            {
                var cashDepositsQ = bdays.SelectMany(bd => bd.DEPOSIT).Where(d => d.Type != null && d.Type == DEPOSIT.CONST_TYPE_END_DAY_CASH);
                if (cashDepositsQ.Any())
                {
                    DEPOSIT firstDeposit = cashDepositsQ.First();
                    cashDeposits = cashDepositsQ.Sum(d => d.Amount);

                    if (bdays.Count() == 1)
                    {
                        if (firstDeposit.Notes != null)
                        {
                            notes = firstDeposit.Notes;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return cashDeposits;
        }

        public static decimal GetCheckDepositInfo(IEnumerable<BUSINESS_DAY> bdays, out string notes)
        {
            notes = "N/A";
            decimal checkDeposits = 0;
            try
            {
                var checkDepositsQ = bdays.SelectMany(bd => bd.DEPOSIT).Where(d => d.Type != null && d.Type == DEPOSIT.CONST_TYPE_END_DAY_CHECKS);
                if (checkDepositsQ.Any())
                {
                    DEPOSIT firstDeposit = checkDepositsQ.First();
                    checkDeposits = checkDepositsQ.Sum(d => d.Amount);

                    if (bdays.Count() == 1)
                    {
                        if (firstDeposit.Notes != null)
                        {
                            notes = firstDeposit.Notes;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return checkDeposits;
        }

        public static decimal GetGeneralNotes(IEnumerable<BUSINESS_DAY> bdays, out string weather, out string pmNotes)
        {
            pmNotes = "N/A";
            weather = "N/A";
            decimal checkDeposits = 0;
            try
            {
                if (bdays.Count() == 1)
                {
                    BUSINESS_DAY first = bdays.First();
                    pmNotes = first.PMNotes;
                    weather = first.WeatherSummary;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return checkDeposits;
        }

        public static decimal GetOverage(decimal cashDeposits,
            decimal checkDeposits,
            decimal cashTotal,
            decimal checkTotal,
            decimal bDayStart,
            decimal paidOuts,
            decimal paidIns,
            decimal autoGratuity,
            decimal employeeTips)
        {
            return (cashDeposits + checkDeposits)
                    - cashTotal
                    - checkTotal
                    - bDayStart
                    + paidOuts
                    - paidIns
                    + autoGratuity
                    + employeeTips;
        }

        public static IEnumerable<GetCalls.SalesNumbersView> GetRoundedAdjustedSalesFigures(IEnumerable<BUSINESS_DAY> bdays,
            out decimal compCount,
            out decimal promoCount,
            out decimal voidCount,
            out decimal totalComps,
            out decimal totalVoids,
            out decimal totalPromos,
            out decimal grossSales,
            decimal netSales,
            DominicaEntities context
            )
        {
            IEnumerable<GetCalls.SalesNumbersView> numbers = null;
            compCount = 0;
            promoCount = 0;
            voidCount = 0;
            totalComps = 0;
            totalVoids = 0;
            totalPromos = 0;
            grossSales = 0;

            try
            {

                List<SALE> salesList = GetNonSeeServerSales(bdays);

                numbers = from s in salesList
                          let DiscountAmountL = s.CountOrdered * (s.DiscountRate * s.ActualPrice)
                          let DiscountedPriceL = (s.CountOrdered * s.ActualPrice) - DiscountAmountL
                          let WasCompedL = s.WasCompedInEntire ? 1 : 0
                          let WasVoidedL = s.WasVoided ? 1 : 0
                          let WasPromodL = (!s.WasCompedInEntire && !s.WasVoided && s.DiscountId != null) ? 1 : 0

                          select new GetCalls.SalesNumbersView()
                          {
                              CountOrdered = s.CountOrdered,
                              DiscountedPrice = DiscountedPriceL,
                              DiscountAmount = DiscountAmountL,
                              GrossPrice = s.ActualPrice * s.CountOrdered,
                              WasComped = WasCompedL,
                              WasVoided = WasVoidedL,
                              WasPromod = WasPromodL,
                              CompAmount = WasCompedL == 1 ? s.ActualPrice * s.CountOrdered : 0,
                              VoidAmount = WasVoidedL == 1 ? s.ActualPrice * s.CountOrdered : 0,
                              PromoAmount = WasPromodL == 1 ? DiscountAmountL : 0,
                              RevTypeId = s.RevenueTypeId,
                              DayPartId = s.DaypartId,
                              RevCenterId = s.RevenueCenterId,
                              ProductId = s.ProductId,
                              IsExceptionMod = s.IsExceptionModifier,
                              IsForcedMod = s.IsForcedModifier,
                              UserId = s.UserId,
                              ProductGroup = s.ProductsMainCatId,
                              DayOfWeek = s.FirstOrderedDateTime.DayOfWeek
                          }
                              into sales
                              select sales;

                if (numbers.Any())
                {
                    List<GetCalls.SalesNumbersView> listk = numbers.Where(s => s.WasPromod == 1).ToList();
                    compCount = numbers.Sum(s => s.WasComped);
                    promoCount = numbers.Sum(s => s.WasPromod);
                    voidCount = numbers.Sum(s => s.WasVoided);
                    totalComps = Math.Round(numbers.Sum(s => s.CompAmount), 2, MidpointRounding.AwayFromZero);
                    totalVoids = Math.Round(numbers.Sum(s => s.VoidAmount), 2, MidpointRounding.AwayFromZero);
                    totalPromos = Math.Round(numbers.Sum(s => s.PromoAmount), 2, MidpointRounding.AwayFromZero);
                    grossSales = numbers.Sum(s => s.GrossPrice);

                    decimal discounts = (totalComps + totalPromos + totalVoids);
                    decimal error = discounts - (grossSales - netSales);
                    grossSales += error;
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }

            return numbers;
        }

        public static List<GetCalls.DisplaySaleByRevType> GetSalesBy(List<BUSINESS_DAY> bdays, REPORT_TYPE_ENUM CurrentReport)
        {
            List<GetCalls.DisplaySaleByRevType> list = new List<GetCalls.DisplaySaleByRevType>();
            try
            {
                using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
                {
                    GetCalls.DisplaySaleByRevType first = new GetCalls.DisplaySaleByRevType();
                    SYSCONFIG sysCfg = SYSCONFIG.Get(context);
                    first.ReportAddress1 = sysCfg.ReceiptLine1;
                    first.ReportAddress2 = sysCfg.ReceiptLine2;
                    first.ReportAddress3 = sysCfg.ReceiptLine3;

                    if (bdays == null)
                    {
                        bdays = context.BUSINESS_DAYS.Where(b => b.BusinessDayDateStamp != null && b.BusinessDayDateStamp >= GetCalls.ReportStartDate &&
                            b.BusinessDayDateStamp <= GetCalls.ReportEndDate).ToList();
                    }
                    GetCalls.SetReportDateTime(bdays, context);

                    first.ReportRange = GetCalls.ReportStartDate.ToString("MM/dd/yy", CultureInfo.CreateSpecificCulture("en-US"));
                    first.ReportRange += GetCalls.ReportStartDate.ToString(" h:mm tt", CultureInfo.CreateSpecificCulture("en-US"));
                    first.ReportRange += " to ";
                    first.ReportRange += GetCalls.ReportEndDate.ToString("MM/dd/yy", CultureInfo.CreateSpecificCulture("en-US"));
                    first.ReportRange += GetCalls.ReportEndDate.ToString(" h:mm tt", CultureInfo.CreateSpecificCulture("en-US"));


                    GetCalls.DisplayMasterSalesReport temp = new GetCalls.DisplayMasterSalesReport();
                    temp.InitDisplayMasterSalesReport();
                    temp.NetSales = CommonCalls.GetNetSales(bdays);
                    IEnumerable<GetCalls.SalesNumbersView> salesList = GetRoundedAdjustedSalesFigures(bdays,
                        out GetCalls.DisplayMasterSalesReport.compCount,
                        out GetCalls.DisplayMasterSalesReport.promoCount,
                        out GetCalls.DisplayMasterSalesReport.voidCount,
                        out GetCalls.DisplayMasterSalesReport.totalComps,
                        out GetCalls.DisplayMasterSalesReport.totalVoids,
                        out GetCalls.DisplayMasterSalesReport.totalPromos,
                        out GetCalls.DisplayMasterSalesReport.grossSales,
                        temp.NetSales,
                        context);

                    if (salesList != null && salesList.Any())
                    {
                        List<Int64> disctinctIds = null;

                        if (CurrentReport == REPORT_TYPE_ENUM.SALES_DAYPART)
                        {
                            disctinctIds = salesList.Select(s => s.DayPartId).Distinct().ToList();
                            first.ReportName = sysCfg.ReceiptLine1 + " - " + "Sales by Daypart";
                            first.SortFieldName = "Daypart";
                            first.SortFieldSentence = "Totals for all Dayparts";
                        }
                        else if (CurrentReport == REPORT_TYPE_ENUM.SALES_DAYOFWEEK)
                        {
                            List<DayOfWeek> daysOfWeek = salesList.OrderBy(s=>s.DayOfWeek).Select(s => s.DayOfWeek).Distinct().ToList();
                            first.ReportName = sysCfg.ReceiptLine1 + " - " + "Sales by Day of Week";
                            first.SortFieldName = "Day of Week";
                            first.SortFieldSentence = "Totals for all Days";

                            foreach(DayOfWeek dow in daysOfWeek)
                            {
                                   foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in salesList
                                        .Where(s => s.DayOfWeek == dow)
                                        .GroupBy(g => g.ProductGroup)
                                        .OrderByDescending
                                        (g => g.Sum(s => s.DiscountedPrice)))
                                    {
                                        GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                        FillDataFields(salesGroups, context, display, temp, list);
                                        display.RevenueTypeName = dow.ToString();
                                    }
                            }
                        }
                        else if (CurrentReport == REPORT_TYPE_ENUM.SALES_EMPLOYEE)
                        {
                            disctinctIds = salesList.Select(s => s.UserId).Distinct().ToList();
                            first.ReportName = sysCfg.ReceiptLine1 + " - " + "Sales by Employee";
                            first.SortFieldName = "Employee";
                            first.SortFieldSentence = "Totals for all Employees";
                        }
                        else if (CurrentReport == REPORT_TYPE_ENUM.SALES_PRODUCTGROUP)
                        {
                            first.ReportName = sysCfg.ReceiptLine1 + " - " + "Sales by Product Group";
                            first.SortFieldName = "Product Group";
                            first.SortFieldSentence = "Totals for all Product Groups";

                            var a1 = salesList.Where(s => !s.IsForcedMod && !s.IsExceptionMod).Select(s => s.ProductGroup).Distinct();
                            if (a1.Any())
                            {
                                foreach (Int64 id in a1.ToList())
                                {
                                    var v1 = salesList.Where(s => s.ProductGroup == id && !s.IsExceptionMod && !s.IsForcedMod).GroupBy(g => g.ProductId);
                                    if (v1.Any())
                                    {
                                        var b1 = v1.OrderByDescending(g => g.Sum(s => s.DiscountedPrice));
                                        foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in b1)
                                        {
                                            GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                            FillDataFields(salesGroups, context, display, temp, list);
                                            display.RevenueTypeName = context.PRODUCT_GROUPS.Where(rc => rc.Id == id).First().Name;
                                        }
                                    }
                                }
                            }

                            var a2 = salesList.Where(s => s.IsForcedMod == true).Select(s => s.ProductGroup).Distinct();
                            if (a2.Any())
                            {
                                foreach (Int64 id in a2.ToList())
                                {
                                    var v3 = salesList.Where(s => s.ProductGroup == id && s.IsForcedMod == true).GroupBy(g => g.ProductId);
                                    if (v3.Any())
                                    {
                                        var b3 = v3.OrderByDescending(g => g.Sum(s => s.DiscountedPrice));
                                        foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in b3)
                                        {
                                            GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                            FillDataFields(salesGroups, context, display, temp, list);
                                            display.RevenueTypeName = context.FORCED_MODIFIER_GROUPS.Where(rc => rc.Id == id).First().Name;
                                        }
                                    }
                                }
                            }

                            var a3 = salesList.Where(s => s.IsExceptionMod).Select(s => s.ProductGroup).Distinct();
                            if (a3.Any())
                            {
                                foreach (Int64 id in a3.ToList())
                                {
                                    var v3 = salesList.Where(s => s.ProductGroup == id && s.IsExceptionMod).GroupBy(g => g.ProductId);
                                    if (v3.Any())
                                    {
                                        var b3 = v3.OrderByDescending(g => g.Sum(s => s.DiscountedPrice));
                                        foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in b3)
                                        {
                                            GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                            FillDataFields(salesGroups, context, display, temp, list);
                                            display.RevenueTypeName = context.EXCEPTION_MODIFIER_GROUPS.Where(rc => rc.Id == id).First().Name;
                                        }
                                    }
                                }
                            }
                        }
                        else if (CurrentReport == REPORT_TYPE_ENUM.SALES_REVCENTER)
                        {
                            disctinctIds = salesList.Select(s => s.RevCenterId).Distinct().ToList();
                            first.ReportName = sysCfg.ReceiptLine1 + " - " + "Sales by Revenue Center";
                            first.SortFieldName = "Revenue Center";
                            first.SortFieldSentence = "Totals for all Revenue Centers";
                        }
                        else if (CurrentReport == REPORT_TYPE_ENUM.SALES_REVTYPE)
                        {
                            disctinctIds = salesList.Select(s => s.RevTypeId).Distinct().ToList();
                            first.ReportName = sysCfg.ReceiptLine1 + " - " + "Sales by Revenue Type";
                            first.SortFieldName = "Revenue Type";
                            first.SortFieldSentence = "Totals for all Revenue Types";
                        }

                        if (CurrentReport != REPORT_TYPE_ENUM.SALES_PRODUCTGROUP && CurrentReport != REPORT_TYPE_ENUM.SALES_DAYOFWEEK)
                        {
                            foreach (Int64 id in disctinctIds)
                            {
                                if (CurrentReport == REPORT_TYPE_ENUM.SALES_DAYPART)
                                {
                                    foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in salesList
                                        .Where(s => s.DayPartId == id)
                                        .GroupBy(g => g.ProductId)
                                        .OrderByDescending
                                        (g => g.Sum(s => s.DiscountedPrice)))
                                    {
                                        GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                        FillDataFields(salesGroups, context, display, temp, list);
                                        display.RevenueTypeName = context.DAYPARTS.Where(rc => rc.Id == id).First().Name;
                                    }

                                }
                                else if (CurrentReport == REPORT_TYPE_ENUM.SALES_EMPLOYEE)
                                {
                                    foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in salesList
                                        .Where(s => s.UserId == id)
                                        .GroupBy(g => g.ProductId)
                                        .OrderByDescending
                                        (g => g.Sum(s => s.DiscountedPrice)))
                                    {
                                        GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                        FillDataFields(salesGroups, context, display, temp, list);
                                        USER user = context.USERS.Where(rc => rc.Id == id).First();
                                        display.RevenueTypeName = user.FirstName + " " + user.LastName;
                                    }

                                }
                                else if (CurrentReport == REPORT_TYPE_ENUM.SALES_REVCENTER)
                                {
                                    foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in salesList
                                        .Where(s => s.RevCenterId == id)
                                        .GroupBy(g => g.ProductId)
                                        .OrderByDescending
                                        (g => g.Sum(s => s.DiscountedPrice)))
                                    {
                                        GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                        FillDataFields(salesGroups, context, display, temp, list);
                                        display.RevenueTypeName = context.REVENUE_CENTERS.Where(rc => rc.Id == id).First().Name;
                                    }

                                }
                                else if (CurrentReport == REPORT_TYPE_ENUM.SALES_REVTYPE)
                                {
                                    foreach (IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups in salesList
                                        .Where(s => s.RevTypeId == id)
                                        .GroupBy(g => g.ProductId)
                                        .OrderByDescending
                                        (g => g.Sum(s => s.DiscountedPrice)))
                                    {
                                        GetCalls.DisplaySaleByRevType display = new GetCalls.DisplaySaleByRevType();
                                        FillDataFields(salesGroups, context, display, temp, list);
                                        display.RevenueTypeName = context.REVENUE_TYPES.Where(rc => rc.Id == id).First().Name;
                                    }

                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
            return list;
        }

        private static void FillDataFields(IGrouping<Int64, GetCalls.SalesNumbersView> salesGroups, DominicaEntities context,
            GetCalls.DisplaySaleByRevType display,
            GetCalls.DisplayMasterSalesReport temp,
            List<GetCalls.DisplaySaleByRevType> list)
        {
            GetCalls.SalesNumbersView numbers = null;
            numbers = salesGroups.First();
            display.Count = salesGroups.Sum(s => s.CountOrdered);
            long productId = numbers.ProductId;
            if (numbers.IsForcedMod)
            {
                display.ProductName = context.FORCED_MODIFIERS.Where(f => f.Id == productId).First().Name;
            }
            else if (numbers.IsExceptionMod)
            {
                display.ProductName = context.EXCEPTION_MODIFIERS.Where(f => f.Id == productId).First().Name;
            }
            else
            {
                display.ProductName = context.PRODUCTS.Where(f => f.Id == productId).First().Name;
            }

            display.TotalRevenue = Math.Round(salesGroups.Sum(s => s.DiscountedPrice), 2, MidpointRounding.AwayFromZero);
            display.TotalMenuPrice = Math.Round(salesGroups.Sum(s => s.GrossPrice), 2, MidpointRounding.AwayFromZero);
            display.TotalDiscount = Math.Round(salesGroups.Sum(s => s.DiscountAmount), 2, MidpointRounding.AwayFromZero);

            display.PercentOfSales = display.TotalMenuPrice / GetCalls.DisplayMasterSalesReport.grossSales;
            list.Add(display);

            display.NetTotal = temp.NetSales;
            display.GrossTotal = temp.GrossSales;
            display.GrossDiscounts = temp.GrossSales - temp.NetSales;
        }

        public static void GetSalesByRevTypeInfo(IEnumerable<BUSINESS_DAY> bdays,
            GetCalls.DisplayMasterSalesReport first,
            List<GetCalls.DisplayMasterSalesReport> list)
        {
            try
            {
                using (DominicaEntities context = new DominicaEntities(DominicaEntities.GetEfConString()))
                {
                    IEnumerable<GetCalls.SalesNumbersView> salesNumbers = GetRoundedAdjustedSalesFigures(bdays,
                        out GetCalls.DisplayMasterSalesReport.compCount,
                        out GetCalls.DisplayMasterSalesReport.promoCount,
                        out GetCalls.DisplayMasterSalesReport.voidCount,
                        out GetCalls.DisplayMasterSalesReport.totalComps,
                        out GetCalls.DisplayMasterSalesReport.totalVoids,
                        out GetCalls.DisplayMasterSalesReport.totalPromos,
                        out GetCalls.DisplayMasterSalesReport.grossSales,
                        first.NetSales,
                        context);

                    if (salesNumbers != null)
                    {
                        var revenueTypeGroup = from r in salesNumbers
                                               group r by r.RevTypeId into grouping
                                               select grouping;

                        if (revenueTypeGroup.Any())
                        {
                            bool isFirst = true;
                            foreach (IGrouping<long, GetCalls.SalesNumbersView> groups in revenueTypeGroup)
                            {
                                if (groups.Sum(s => s.GrossPrice) != 0)
                                {
                                    GetCalls.SalesNumbersView view = groups.First();
                                    GetCalls.DisplayMasterSalesReport report;

                                    if (isFirst)
                                    {
                                        report = first;
                                    }
                                    else
                                    {
                                        report = new GetCalls.DisplayMasterSalesReport();
                                    }

                                    if (context.REVENUE_TYPES.Where(rt => rt.Id == view.RevTypeId).Any())
                                    {
                                        report.RevenueType = context.REVENUE_TYPES.Where(rt => rt.Id == view.RevTypeId).First().Name;
                                        report.GrossSalesForRevType = groups.Sum(s => s.GrossPrice);

                                        if (groups.Where(s => s.WasComped == 0 && s.WasVoided == 0).Any())
                                        {
                                            report.NetSalesForRevenueType = groups.Where(s => s.WasComped == 0 && s.WasVoided == 0).Sum(s => s.DiscountedPrice);
                                        }
                                        if (groups.Where(s => s.WasComped == 1).Any())
                                        {
                                            report.Comps = groups.Where(s => s.WasComped == 1).Sum(s => s.GrossPrice);
                                        }
                                        if (groups.Where(s => s.WasVoided == 1).Any())
                                        {
                                            report.Voids = groups.Where(s => s.WasVoided == 1).Sum(s => s.GrossPrice);
                                        }
                                        if (groups.Where(s => s.WasPromod == 1).Any())
                                        {
                                            report.Promos = groups.Where(s => s.WasPromod == 1).Sum(s => s.DiscountAmount);
                                        }

                                        if (!isFirst)
                                        {
                                            list.Add(report);
                                        }
                                        else
                                        {
                                            isFirst = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }

        public static void GetTransactionalInfo(IEnumerable<BUSINESS_DAY> bdays,
                        GetCalls.DisplayMasterSalesReport first)
        {
            try
            {
                List<ORDER> ordersList = GetOrders(bdays);

                var transactionsQ = (from t in ordersList.SelectMany(o => o.TRANSACTIONS.Where(t => t.WasVoided == false))
                                     select new GetCalls.TransactionNumbersView()
                                     {
                                         TotalSale = t.Base,
                                         GratuityAmount = t.Gratuity,
                                         TenderType = t.TenderType
                                     }
                                         into transactions
                                         select transactions).GroupBy(t => t.TenderType);

                if (transactionsQ.Any())
                {
                    foreach (IGrouping<int, GetCalls.TransactionNumbersView> tGroups in transactionsQ)
                    {
                        first.PaymentsTotal += tGroups.Sum(t => t.TotalSale);
                        first.GratuityTotal += tGroups.Sum(t => t.GratuityAmount);

                        if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_ACCOUNT)
                        {
                            first.HouseAccountTotal = tGroups.Sum(s => s.TotalSale);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_AMEX)
                        {
                            first.AmexTotal = tGroups.Sum(s => s.TotalSale);
                            first.AmexGrat = tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_CASH)
                        {
                            first.CashTotal = tGroups.Sum(s => s.TotalSale);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_CHECK)
                        {
                            first.CheckTotal = tGroups.Sum(s => s.TotalSale);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_DISC)
                        {
                            first.DiscoverTotal = tGroups.Sum(s => s.TotalSale);
                            first.DiscoverGrat = tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_DNCLB)
                        {
                            first.OtherEdcTotal += tGroups.Sum(s => s.TotalSale);
                            first.OtherEdcGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_GIFT)
                        {
                            first.GiftTotal += tGroups.Sum(s => s.TotalSale);
                            first.GiftGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_JCB)
                        {
                            first.OtherEdcTotal += tGroups.Sum(s => s.TotalSale);
                            first.OtherEdcGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_OTHER)
                        {
                            first.OtherEdcTotal += tGroups.Sum(s => s.TotalSale);
                            first.OtherEdcGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_MC)
                        {
                            first.MasterCardTotal += tGroups.Sum(s => s.TotalSale);
                            first.MasterGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                        else if (tGroups.First().TenderType == TRANSACTION.CONST_TENDER_VISA)
                        {
                            first.VisaTotal += tGroups.Sum(s => s.TotalSale);
                            first.VisaGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                        else
                        {
                            first.OtherEdcTotal += tGroups.Sum(s => s.TotalSale);
                            first.OtherEdcGrat += tGroups.Sum(s => s.GratuityAmount);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logging.LogException(ex);
            }
        }
    }
}
